package com.iddaa.web.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.iddaa.web.util.Response;

@Aspect
@Component("responseAspect")
public class ResponseAspect {

	private Logger logger = LoggerFactory.getLogger(ResponseAspect.class);

	@Around("inWebLayer() && !isCustomResponse()")
	public Object prepareResponse(ProceedingJoinPoint proceedingJoinPoint) {
		Response response = null;
		try {
			response = (Response) proceedingJoinPoint.proceed();
		} catch (Throwable e) {
			logger.error(new StringBuilder("Exception caught on ").append(proceedingJoinPoint.getTarget().getClass().getSimpleName()).toString(), e);
			response = new Response(null);
			response.addError(e);
		}
		return response;
	}

	@Pointcut("execution(* com.iddaa.web.resource..*.*(..))")
	public void inWebLayer() {
	}

	@Pointcut("@annotation(com.iddaa.web.annotation.CustomResponse)")
	public void isCustomResponse() {
	}

}
